


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@WebServlet("/uploadFile")
public class UploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    public static final String UPLOAD_PATH = "E:/upload";


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> list = upload.parseRequest(request);
            for(FileItem fi : list) {
                if(fi.isFormField()) {
                    //上传的不是文件
                } else {
                    String sourceName = fi.getName();
                    // 获取文件扩展名
                    String fileExt = sourceName.substring(sourceName.lastIndexOf("."));
                    // 检查文件类型是否为jpg、png或gif
                    if (fileExt.equalsIgnoreCase(".jpg") || fileExt.equalsIgnoreCase(".png") || fileExt.equalsIgnoreCase(".gif")) {
                        //文件保存目录
                        File file = new File(UPLOAD_PATH);
                        if(!file.exists()) {
                            file.mkdirs();
                        }
                        //为了避免文件名重复，使用源文件名+uuid+后缀格式存储
                        String fileName = sourceName.substring(0,sourceName.lastIndexOf('.'))+ "-" +UUID.randomUUID().toString()+fileExt;
                        System.out.println(fileName);
                        fi.write(new File(UPLOAD_PATH + "/" + fileName));
                        //保存到数据库
                        SaveDao saveDao = new SaveDao();
                        saveDao.saveFileInfo(fileName, file.getAbsolutePath());
                    } else {
                        // 文件类型不符合要求的提示信息
                        request.setAttribute("message", "请上传.jpg .png或.gif格式的文件");

                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.getRequestDispatcher("index.jsp").forward(request, response);
    }







}
